package com.hn.zhijian.base.data.config.mybatis;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.hn.zhijian.base.common.ConfigurationYmlProperty;
import com.hn.zhijian.base.data.common.DBLoadSource;
import com.hn.zhijian.base.data.common.DBType;
import com.hn.zhijian.base.data.common.DynamicDataSource;
import com.hn.zhijian.base.data.common.IDataSource;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.apache.ibatis.type.JdbcType;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author carl
 * @date 2018/2/6.
 */
@Configuration
@DependsOn(value = "applicationBeanUtil")
public class MybatisPlusConfig {

    @Autowired
    private MybatisPlusProperty mybatisPlusProperty;

    @Autowired
    private ConfigurationYmlProperty configurationYmlProperty;

    /**
     * mybatis-plus分页插件<br>
     * 文档：http://mp.baomidou.com<br>
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        return paginationInterceptor;
    }

    /**
     * mybatis-plus SQL执行效率插件【生产环境可以关闭】
     */
    @Bean
    public PerformanceInterceptor performanceInterceptor() {
        return new PerformanceInterceptor();
    }

    /**
     * 动态数据源配置
     *
     * @return
     */
    @Bean
    @Primary
    public DataSource multipleDataSource() {

        DynamicDataSource dynamicDataSource = new DynamicDataSource();

        Map<Object, Object> targetDataSources = new HashMap<>();

        for (Map.Entry<String, IDataSource> entry : DBLoadSource.instance().getDataSources().entrySet()) {
            String mapKey = entry.getKey();

            IDataSource dataSource = entry.getValue();
            //设置数据源
            targetDataSources.put(dataSource.dbName(),dataSource.dataSurSource());
            //把所有数据源加入数据库
            DBType.instance().setListName(mapKey);
        }
        //加载所有的数据源
        dynamicDataSource.setTargetDataSources(targetDataSources);

        //加载默认数据源
        dynamicDataSource.setDefaultTargetDataSource(targetDataSources.get(configurationYmlProperty.getDefaultName()));
        return dynamicDataSource;
    }

    @Bean
    public DataSourceTransactionManager transactionManager(DataSource dataSource) throws Exception {
        return new DataSourceTransactionManager(dataSource);
    }


    @Bean("sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(GlobalConfig globalConfig) throws Exception {

        MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();

        //加载数据源
        sqlSessionFactory.setDataSource(multipleDataSource());

        //加载配置文件
        sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(mybatisPlusProperty.getMapperLocations()));

        MybatisConfiguration configuration = new MybatisConfiguration();

        configuration.setJdbcTypeForNull(JdbcType.NULL);

        configuration.setMapUnderscoreToCamelCase(true);

//        configuration.setCacheEnabled(false);

        sqlSessionFactory.setConfiguration(configuration);

        //加载分页
        sqlSessionFactory.setPlugins(new Interceptor[]{
                paginationInterceptor()
        });

        sqlSessionFactory.setGlobalConfig(globalConfig);

        return sqlSessionFactory.getObject();
    }

//
    @Bean
    public GlobalConfig globalConfiguration() {
        GlobalConfig globalConfig = new GlobalConfig();
        GlobalConfig.DbConfig dbConfig = new GlobalConfig.DbConfig();
        dbConfig.setDbType(DbType.MYSQL);
//        dbConfig.setDbType(DbType.ORACLE);
        dbConfig.setIdType(IdType.AUTO);
        //dbConfig.setTablePrefix("tbl_");  // 关键
        globalConfig.setDbConfig(dbConfig);
        //设置时间
        globalConfig.setMetaObjectHandler(new MyMetaObjectHandler());
        return globalConfig;

    }

}
